<template>
  <div class="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
    <!-- 工具栏 -->
    <div class="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
      <div class="flex items-center justify-between px-6 py-4">
        <!-- 左侧标题和控制 -->
        <div class="flex items-center space-x-4">
          <h1 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
            <i class="fas fa-project-diagram text-blue-500 mr-3"></i>
            智能流程图工具
          </h1>
          
          <!-- 输入模式切换 -->
          <div class="flex bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
            <button
              @click="inputMode = 'mermaid'"
              :class="[
                'px-4 py-2 text-sm font-medium rounded-md transition-all',
                inputMode === 'mermaid' 
                  ? 'bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm' 
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
              ]"
            >
              <i class="fas fa-code mr-2"></i>Mermaid
            </button>
            <button
              @click="inputMode = 'markdown'"
              :class="[
                'px-4 py-2 text-sm font-medium rounded-md transition-all',
                inputMode === 'markdown' 
                  ? 'bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm' 
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
              ]"
            >
              <i class="fab fa-markdown mr-2"></i>Markdown
            </button>
          </div>
        </div>

        <!-- 右侧操作按钮 -->
        <div class="flex items-center space-x-3">
          <!-- 主题选择 -->
          <select 
            v-model="selectedTheme" 
            @change="handleThemeChange"
            class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
          >
            <option value="default">默认主题</option>
            <option value="base">基础主题</option>
            <option value="dark">深色主题</option>
            <option value="forest">森林主题</option>
            <option value="neutral">中性主题</option>
          </select>

          <!-- 自动渲染开关 -->
          <label class="flex items-center cursor-pointer">
            <input 
              type="checkbox" 
              v-model="autoRender" 
              class="sr-only"
            >
            <div :class="[
              'relative w-11 h-6 rounded-full transition-colors duration-200',
              autoRender ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'
            ]">
              <div :class="[
                'absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transform transition-transform duration-200',
                autoRender ? 'translate-x-5' : 'translate-x-0'
              ]"></div>
            </div>
            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">自动渲染</span>
          </label>

          <!-- 导出按钮 -->
          <div class="relative">
            <button
              @click="showExportMenu = !showExportMenu"
              class="flex items-center px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg transition-colors"
            >
              <i class="fas fa-download mr-2"></i>导出
              <i class="fas fa-chevron-down ml-1"></i>
            </button>
            
            <!-- 导出菜单 -->
            <div v-if="showExportMenu" class="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-gray-700 rounded-lg shadow-lg border border-gray-200 dark:border-gray-600 z-50">
              <div class="py-1">
                <button
                  v-for="format in exportFormats"
                  :key="format.type"
                  @click="exportDiagram(format.type)"
                  class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center"
                >
                  <i :class="format.icon" class="mr-3 w-4"></i>
                  {{ format.label }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="flex-1 flex overflow-hidden">
      <!-- 编辑器面板 -->
      <div 
        class="bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col"
        :style="{ width: leftPanelWidth + 'px' }"
      >
        <!-- 编辑器头部 -->
        <div class="flex-shrink-0 flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <h3 class="font-semibold text-gray-900 dark:text-white flex items-center">
            <i :class="inputMode === 'mermaid' ? 'fas fa-code text-blue-500' : 'fab fa-markdown text-orange-500'" class="mr-2"></i>
            {{ inputMode === 'mermaid' ? 'Mermaid 代码' : 'Markdown 文档' }}
          </h3>
          
          <div class="flex items-center space-x-2">
            <span class="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded">
              {{ content.length }} 字符
            </span>
            <button
              @click="formatContent"
              class="p-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title="格式化代码"
            >
              <i class="fas fa-magic"></i>
            </button>
            <button
              @click="copyContent"
              class="p-2 text-gray-600 dark:text-gray-400 hover:text-green-600 dark:hover:text-green-400 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title="复制内容"
            >
              <i class="fas fa-copy"></i>
            </button>
          </div>
        </div>

        <!-- 编辑器 -->
        <div class="flex-1 relative">
          <textarea
            ref="editorRef"
            v-model="content"
            @input="handleContentChange"
            @keydown="handleKeydown"
            class="w-full h-full p-4 font-mono text-sm bg-transparent border-0 resize-none focus:outline-none text-gray-900 dark:text-gray-100"
            :placeholder="currentPlaceholder"
            spellcheck="false"
          ></textarea>
        </div>

        <!-- 编辑器状态栏 -->
        <div class="flex-shrink-0 px-4 py-2 bg-gray-50 dark:bg-gray-750 border-t border-gray-200 dark:border-gray-700">
          <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
            <div class="flex items-center space-x-4">
              <span>行: {{ currentLine }}</span>
              <span>列: {{ currentColumn }}</span>
              <span v-if="renderTime" class="text-green-600 dark:text-green-400">
                <i class="fas fa-clock mr-1"></i>{{ renderTime }}ms
              </span>
              <span v-if="renderError" class="text-red-600 dark:text-red-400">
                <i class="fas fa-exclamation-triangle mr-1"></i>语法错误
              </span>
            </div>
            <div class="flex items-center space-x-2">
              <button
                @click="insertTemplate"
                class="hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                title="插入模板"
              >
                <i class="fas fa-plus"></i>
              </button>
              <button
                @click="clearContent"
                class="hover:text-red-600 dark:hover:text-red-400 transition-colors"
                title="清空内容"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 调整分隔条 -->
      <div
        @mousedown="startResize"
        class="w-1 bg-gray-200 dark:bg-gray-700 hover:bg-blue-500 cursor-col-resize transition-colors group relative"
      >
        <div class="absolute inset-y-0 -left-1 -right-1 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
          <div class="w-0.5 h-8 bg-blue-500 rounded-full"></div>
        </div>
      </div>

      <!-- 预览面板 -->
      <div class="flex-1 flex flex-col bg-white dark:bg-gray-800">
        <!-- 预览头部 -->
        <div class="flex-shrink-0 flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <h3 class="font-semibold text-gray-900 dark:text-white flex items-center">
            <i class="fas fa-eye text-purple-500 mr-2"></i>
            实时预览
          </h3>
          
          <div class="flex items-center space-x-2">
            <!-- 编辑模式切换 -->
            <div class="flex bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
              <button
                @click="editMode = 'view'"
                :class="[
                  'px-3 py-1 text-xs font-medium rounded transition-all',
                  editMode === 'view' 
                    ? 'bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm' 
                    : 'text-gray-600 dark:text-gray-400'
                ]"
              >
                预览
              </button>
              <button
                @click="editMode = 'edit'"
                :class="[
                  'px-3 py-1 text-xs font-medium rounded transition-all',
                  editMode === 'edit' 
                    ? 'bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm' 
                    : 'text-gray-600 dark:text-gray-400'
                ]"
              >
                编辑
              </button>
            </div>

            <!-- 缩放控制 -->
            <div class="flex items-center space-x-1 bg-gray-100 dark:bg-gray-700 rounded-lg">
              <button
                @click="zoomOut"
                class="p-2 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-l-lg transition-colors"
                title="缩小"
              >
                <i class="fas fa-minus text-xs"></i>
              </button>
              <span class="px-3 py-2 text-xs font-medium text-gray-700 dark:text-gray-300 border-x border-gray-200 dark:border-gray-600">
                {{ Math.round(zoomLevel * 100) }}%
              </span>
              <button
                @click="zoomIn"
                class="p-2 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-r-lg transition-colors"
                title="放大"
              >
                <i class="fas fa-plus text-xs"></i>
              </button>
            </div>

            <!-- 操作按钮 -->
            <button
              @click="fitToWindow"
              class="p-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="适合窗口"
            >
              <i class="fas fa-expand-arrows-alt"></i>
            </button>
            
            <button
              @click="renderDiagram"
              class="p-2 text-gray-600 dark:text-gray-400 hover:text-green-600 dark:hover:text-green-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="手动渲染"
            >
              <i class="fas fa-sync-alt" :class="{ 'animate-spin': isRendering }"></i>
            </button>
          </div>
        </div>

        <!-- 预览内容 -->
        <div class="flex-1 overflow-hidden relative">
          <!-- 渲染区域 -->
          <div 
            ref="canvasRef"
            class="w-full h-full overflow-auto p-4 bg-gradient-to-br from-gray-50 to-white dark:from-gray-800 dark:to-gray-900"
            :style="{ transform: `scale(${zoomLevel})`, transformOrigin: 'top left' }"
          >
            <!-- 空状态 -->
            <div v-if="!content.trim()" class="flex items-center justify-center h-full">
              <div class="text-center text-gray-500 dark:text-gray-400">
                <i class="fas fa-project-diagram text-6xl mb-4 opacity-20"></i>
                <h3 class="text-xl font-medium mb-2">开始创建流程图</h3>
                <p class="text-sm">在左侧编辑器中输入 {{ inputMode === 'mermaid' ? 'Mermaid 语法' : 'Markdown 内容' }}</p>
                <button
                  @click="insertTemplate"
                  class="mt-4 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                >
                  <i class="fas fa-plus mr-2"></i>插入示例
                </button>
              </div>
            </div>

            <!-- 错误状态 -->
            <div v-else-if="renderError" class="flex items-center justify-center h-full">
              <div class="text-center text-red-500 dark:text-red-400 max-w-md">
                <i class="fas fa-exclamation-triangle text-4xl mb-4"></i>
                <h3 class="text-lg font-medium mb-2">渲染错误</h3>
                <p class="text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg mb-4">{{ renderError }}</p>
                <button
                  @click="renderDiagram"
                  class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors"
                >
                  <i class="fas fa-redo mr-2"></i>重试
                </button>
              </div>
            </div>

            <!-- 渲染内容 -->
            <div 
              v-else-if="renderedContent"
              id="diagram-container"
              class="flex items-center justify-center min-h-full"
              v-html="renderedContent"
            ></div>

            <!-- 加载状态 -->
            <div v-if="isRendering" class="absolute inset-0 flex items-center justify-center bg-white/80 dark:bg-gray-800/80 z-10">
              <div class="text-center text-blue-500 dark:text-blue-400">
                <i class="fas fa-spinner fa-spin text-4xl mb-2"></i>
                <p class="text-sm">正在渲染...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 模板选择弹窗 -->
    <div v-if="showTemplateModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-4xl w-full max-h-[80vh] flex flex-col">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
            <i class="fas fa-layer-group mr-2"></i>
            选择模板
          </h3>
          <button
            @click="showTemplateModal = false"
            class="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="flex-1 overflow-auto p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div
              v-for="template in templates"
              :key="template.id"
              @click="useTemplate(template)"
              class="p-4 border border-gray-200 dark:border-gray-600 rounded-lg hover:border-blue-500 dark:hover:border-blue-400 cursor-pointer transition-colors"
            >
              <h4 class="font-medium text-gray-900 dark:text-white mb-2">{{ template.name }}</h4>
              <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">{{ template.description }}</p>
              <div class="text-xs text-gray-500 dark:text-gray-500">{{ template.type }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'

// 响应式状态
const inputMode = ref<'mermaid' | 'markdown'>('mermaid')
const editMode = ref<'view' | 'edit'>('view')
const content = ref('')
const selectedTheme = ref('default')
const autoRender = ref(true)
const isRendering = ref(false)
const renderError = ref('')
const renderTime = ref(0)
const renderedContent = ref('')
const zoomLevel = ref(1)
const leftPanelWidth = ref(500)
const currentLine = ref(1)
const currentColumn = ref(1)
const showExportMenu = ref(false)
const showTemplateModal = ref(false)

// DOM引用
const editorRef = ref<HTMLTextAreaElement>()
const canvasRef = ref<HTMLElement>()

// 导出格式
const exportFormats = [
  { type: 'png', label: 'PNG 图片', icon: 'fas fa-image' },
  { type: 'svg', label: 'SVG 矢量图', icon: 'fas fa-vector-square' },
  { type: 'pdf', label: 'PDF 文档', icon: 'fas fa-file-pdf' },
  { type: 'markdown', label: 'Markdown 源码', icon: 'fab fa-markdown' }
]

// 模板数据
const templates = [
  {
    id: 'flowchart-basic',
    name: '基础流程图',
    description: '简单的决策流程图示例',
    type: 'Mermaid',
    content: `graph TD
    A[开始] --> B{判断条件}
    B -->|是| C[执行操作A]
    B -->|否| D[执行操作B]
    C --> E[结束]
    D --> E`
  },
  {
    id: 'sequence-basic',
    name: '时序图',
    description: '展示对象间交互的时序图',
    type: 'Mermaid',
    content: `sequenceDiagram
    participant A as 用户
    participant B as 系统
    participant C as 数据库
    
    A->>B: 发送请求
    B->>C: 查询数据
    C-->>B: 返回结果
    B-->>A: 响应数据`
  },
  {
    id: 'class-diagram',
    name: '类图',
    description: '面向对象设计的类关系图',
    type: 'Mermaid',
    content: `classDiagram
    class Animal {
        +String name
        +int age
        +eat()
        +sleep()
    }
    
    class Dog {
        +String breed
        +bark()
    }
    
    class Cat {
        +String color
        +meow()
    }
    
    Animal <|-- Dog
    Animal <|-- Cat`
  },
  {
    id: 'markdown-flowchart',
    name: 'Markdown 流程',
    description: '使用Markdown描述的工作流程',
    type: 'Markdown',
    content: `# 项目开发流程

## 1. 需求分析
- 用户调研
- 需求收集
- 可行性分析

## 2. 设计阶段
- 系统架构设计
- UI/UX 设计
- 数据库设计

## 3. 开发阶段
- 前端开发
- 后端开发
- 测试用例编写

## 4. 测试阶段
- 单元测试
- 集成测试
- 用户验收测试

## 5. 部署上线
- 生产环境部署
- 监控配置
- 文档更新`
  }
]

// 计算属性
const currentPlaceholder = computed(() => {
  return inputMode.value === 'mermaid' 
    ? `请输入 Mermaid 语法...

示例：
graph TD
    A[开始] --> B{判断条件}
    B -->|是| C[执行操作]
    C --> D[结束]
    B -->|否| D`
    : `请输入 Markdown 内容...

示例：
# 项目标题
## 主要步骤
- 步骤一
- 步骤二
- 步骤三`
})

// 防抖渲染
let renderTimeout: NodeJS.Timeout
const debouncedRender = () => {
  clearTimeout(renderTimeout)
  renderTimeout = setTimeout(() => {
    renderDiagram()
  }, 500)
}

// 渲染图表
async function renderDiagram() {
  if (!content.value.trim()) {
    renderedContent.value = ''
    renderError.value = ''
    return
  }

  try {
    isRendering.value = true
    renderError.value = ''
    const startTime = performance.now()

    if (inputMode.value === 'mermaid') {
      await renderMermaid()
    } else {
      await renderMarkdown()
    }

    const endTime = performance.now()
    renderTime.value = Math.round(endTime - startTime)
    
  } catch (error) {
    console.error('渲染失败:', error)
    renderError.value = error instanceof Error ? error.message : '渲染失败'
  } finally {
    isRendering.value = false
  }
}

// 渲染Mermaid图表
async function renderMermaid() {
  const mermaid = (await import('mermaid')).default
  
  mermaid.initialize({
    startOnLoad: false,
    theme: selectedTheme.value as any,
    securityLevel: 'loose',
    flowchart: {
      useMaxWidth: true,
      htmlLabels: true
    }
  })

  const diagramId = `diagram-${Date.now()}`
  const { svg } = await mermaid.render(diagramId, content.value)
  
  renderedContent.value = svg
}

// 渲染Markdown
async function renderMarkdown() {
  // 简单的Markdown转HTML渲染
  const markdownIt = (await import('markdown-it')).default
  const md = markdownIt({
    html: true,
    linkify: true,
    typographer: true
  })
  
  const html = md.render(content.value)
  renderedContent.value = `<div class="prose prose-lg max-w-none dark:prose-invert">${html}</div>`
}

// 事件处理函数
function handleContentChange() {
  updateCursorPosition()
  
  if (autoRender.value) {
    debouncedRender()
  }
}

function handleThemeChange() {
  if (autoRender.value) {
    renderDiagram()
  }
}

function handleKeydown(event: KeyboardEvent) {
  // Tab键处理
  if (event.key === 'Tab') {
    event.preventDefault()
    const textarea = event.target as HTMLTextAreaElement
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    
    const beforeCursor = content.value.substring(0, start)
    const afterCursor = content.value.substring(end)
    
    content.value = beforeCursor + '    ' + afterCursor
    
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + 4
    })
  }
  
  // Ctrl+Enter强制渲染
  if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
    event.preventDefault()
    renderDiagram()
  }
}

function updateCursorPosition() {
  if (!editorRef.value) return
  
  const textarea = editorRef.value
  const cursorPos = textarea.selectionStart
  const textBeforeCursor = content.value.substring(0, cursorPos)
  
  currentLine.value = textBeforeCursor.split('\n').length
  currentColumn.value = textBeforeCursor.split('\n').pop()?.length || 0
}

// 功能函数
function formatContent() {
  if (inputMode.value === 'mermaid') {
    // 简单的Mermaid格式化
    const lines = content.value.split('\n')
    let indentLevel = 0
    const formatted = lines.map(line => {
      const trimmed = line.trim()
      if (!trimmed) return ''
      
      if (trimmed.includes('end') || trimmed.includes('}')) {
        indentLevel = Math.max(0, indentLevel - 1)
      }
      
      const indent = '    '.repeat(indentLevel)
      
      if (trimmed.includes('subgraph') || trimmed.includes('{')) {
        indentLevel++
      }
      
      return indent + trimmed
    })
    
    content.value = formatted.join('\n')
  }
}

async function copyContent() {
  try {
    await navigator.clipboard.writeText(content.value)
    // 可以添加成功提示
  } catch (error) {
    console.error('复制失败:', error)
  }
}

function insertTemplate() {
  showTemplateModal.value = true
}

function useTemplate(template: any) {
  content.value = template.content
  inputMode.value = template.type.toLowerCase()
  showTemplateModal.value = false
  
  if (autoRender.value) {
    nextTick(() => {
      renderDiagram()
    })
  }
}

function clearContent() {
  content.value = ''
  renderedContent.value = ''
  renderError.value = ''
}

// 缩放控制
function zoomIn() {
  zoomLevel.value = Math.min(zoomLevel.value + 0.2, 3)
}

function zoomOut() {
  zoomLevel.value = Math.max(zoomLevel.value - 0.2, 0.2)
}

function fitToWindow() {
  zoomLevel.value = 1
}

// 导出功能
async function exportDiagram(format: string) {
  showExportMenu.value = false
  
  try {
    switch (format) {
      case 'png':
        await exportPNG()
        break
      case 'svg':
        await exportSVG()
        break
      case 'pdf':
        console.log('PDF导出功能开发中...')
        break
      case 'markdown':
        await exportMarkdown()
        break
    }
  } catch (error) {
    console.error('导出失败:', error)
  }
}

async function exportSVG() {
  if (!renderedContent.value) return
  
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = renderedContent.value
  const svgElement = tempDiv.querySelector('svg')
  
  if (svgElement) {
    const svgData = new XMLSerializer().serializeToString(svgElement)
    const blob = new Blob([svgData], { type: 'image/svg+xml' })
    downloadBlob(blob, 'diagram.svg')
  }
}

async function exportPNG() {
  if (!renderedContent.value) return
  
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = renderedContent.value
  const svgElement = tempDiv.querySelector('svg')
  
  if (svgElement) {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')!
    const img = new Image()
    
    const svgData = new XMLSerializer().serializeToString(svgElement)
    const svgBlob = new Blob([svgData], { type: 'image/svg+xml' })
    const url = URL.createObjectURL(svgBlob)
    
    img.onload = () => {
      canvas.width = img.width * 2
      canvas.height = img.height * 2
      ctx.scale(2, 2)
      ctx.drawImage(img, 0, 0)
      
      canvas.toBlob((blob) => {
        if (blob) {
          downloadBlob(blob, 'diagram.png')
        }
      }, 'image/png')
      
      URL.revokeObjectURL(url)
    }
    
    img.src = url
  }
}

async function exportMarkdown() {
  const markdownContent = inputMode.value === 'mermaid' 
    ? `# 流程图

\`\`\`mermaid
${content.value}
\`\`\`
`
    : content.value
  
  const blob = new Blob([markdownContent], { type: 'text/markdown' })
  downloadBlob(blob, 'diagram.md')
}

function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 面板调整
let isResizing = false

function startResize(event: MouseEvent) {
  isResizing = true
  document.addEventListener('mousemove', doResize)
  document.addEventListener('mouseup', endResize)
  event.preventDefault()
}

function doResize(event: MouseEvent) {
  if (!isResizing) return
  
  const container = document.querySelector('.h-screen') as HTMLElement
  if (!container) return
  
  const containerRect = container.getBoundingClientRect()
  const newWidth = event.clientX - containerRect.left
  
  leftPanelWidth.value = Math.max(300, Math.min(window.innerWidth * 0.7, newWidth))
}

function endResize() {
  isResizing = false
  document.removeEventListener('mousemove', doResize)
  document.removeEventListener('mouseup', endResize)
}

// 点击外部关闭菜单
function handleClickOutside(event: Event) {
  const target = event.target as HTMLElement
  if (showExportMenu.value && !target.closest('.relative')) {
    showExportMenu.value = false
  }
}

// 生命周期
onMounted(() => {
  // 设置默认内容
  content.value = templates[0].content
  
  // 初始渲染
  nextTick(() => {
    renderDiagram()
  })
  
  // 添加事件监听
  document.addEventListener('click', handleClickOutside)
  
  // 监听编辑器光标位置
  if (editorRef.value) {
    editorRef.value.addEventListener('selectionchange', updateCursorPosition)
  }
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  document.removeEventListener('mousemove', doResize)
  document.removeEventListener('mouseup', endResize)
  clearTimeout(renderTimeout)
})

// 监听器
watch(() => inputMode.value, () => {
  if (autoRender.value) {
    renderDiagram()
  }
})

watch(() => selectedTheme.value, () => {
  if (autoRender.value && inputMode.value === 'mermaid') {
    renderDiagram()
  }
})
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-auto::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.overflow-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-auto::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.overflow-auto::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.dark .overflow-auto::-webkit-scrollbar-thumb {
  background: #475569;
}

/* 编辑器样式 */
textarea {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  line-height: 1.6;
  letter-spacing: 0.025em;
}

/* 渲染内容样式 */
#diagram-container {
  min-height: 400px;
}

#diagram-container svg {
  max-width: 100%;
  height: auto;
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.1));
}

.dark #diagram-container svg {
  filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.3));
}

/* Prose 样式 */
.prose {
  max-width: none;
}

.prose h1,
.prose h2,
.prose h3,
.prose h4,
.prose h5,
.prose h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
}

.prose ul,
.prose ol {
  margin: 1em 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .flex-col {
    flex-direction: column;
  }
  
  .border-r {
    border-right: none;
    border-bottom: 1px solid;
  }
}

/* 过渡动画 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 0.15s;
}

/* 加载动画 */
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style> 